import {
    request,
    summary,
    body,
    tags,
    middlewares,
    path as rpath,
    query,
    description
} from '../swagger';
import { APIError } from "../helper/rest";
import { getIp, responseWrapper,writeFile, readFile, exec } from "../helper/util";
import config from '../config';
const session = require('koa-session')
const Note = require('../model/note')
var fs = require('fs')
var path = require('path')
var mime = require('mime')
var mkdirp = require('mkdirp')

var fileDir = path.join(config.fileDir, 'files')

function createFolderIfNeeded(path) {
    if (!fs.existsSync(path)) {
        mkdirp.sync(path, function(err) {
            if (err) console.error(err)
        })
    }
}

async function saveFile(data) {
    if(!data.fileName){
        throw (new Error("没有文件名称"))
    }
    if(!data.fileContent){
        throw (new Error("没有文本内容"))
    }
    var fileName = data.fileName ;

    var fileRelatePath = '';//path.join(fileName)用于预备多版本控制
    createFolderIfNeeded(path.join(fileDir, fileRelatePath))
    var fileRealPath = path.join(fileDir, fileRelatePath, fileName + '.text')

    await writeFile(fileRealPath, data.fileContent.toString());

    return { 'downloadUrl': `${config.baseUrl}/api/note/download/${fileName}?fileName=${fileName}.text`}
}
async function parserText(data) {
    var fileName = data.fileName ;
    var fileRealPath = path.join(fileDir, fileName + '.text')
    var fileContent = await readFile(fileRealPath);
     console.log('parserText',fileContent);
    return fileContent.toString()
}

const tag = tags(['笔记本']);

var note = {
    'fileName': 'string',
    'fileContent': 'string',
    'downloadUrl': 'string',
    'isLock': 'boolean'
}
module.exports = class NoteRouter {

    @request('post', '/api/note/update/{id}')
    @summary("更新笔记")
    @tag
    @rpath({ id: { type: 'string', require: true } })
    static async updateNote(ctx, next) {
        var body = ctx.request.body
        var result = await saveFile(body);
        var user = ctx.state.user;
        var fileName = body.fileName ;
        var note = await Note.findOne({'fileName': fileName })
        var nowDate = new Date()
        if (!note) {
            var info ={ fileName:fileName,downloadUrl:result.downloadUrl,isLock :false,updateAt:nowDate,createAt:nowDate}
            note = new Note(info)
            await note.save()
        }else {
            await Note.updateOne({ _id: note._id },{ownerId:user.userId,isLock :false,updateAt:nowDate})
        }
        ctx.body = responseWrapper(result);
    }


    @request('get', '/api/note/{id}')
    @summary("笔记详情")
    @tag
    @body(note)
    @rpath({ id: { type: 'string', required: true } })
    static async getNoteDetail(ctx, next) {
        var user = ctx.state.user
        var { id } = ctx.validatedParams;
        var fileContent = await parserText({fileName:id });
        var note = await Note.findOne({'fileName': id })
         console.log('user',user)
        if(note.isLock && note.ownerId != user.userId ){
            throw new Error("笔记被锁定，没有权限")
        }else {
            note.isLock = true; //锁定
            note.ownerId =user.userId
            await note.save()
        }
        if(note && fileContent){
            note.fileContent = fileContent;
        }
        ctx.body = responseWrapper(note)
    }

    @request('get', '/api/notes')
    @summary("获取列表")
    // @query(
    //     {
    //     page:{type:'number',default:0,description:'分页页码(可选)'},
    //     size:{type:'number',default:10,description:'每页条数(可选)'}
    // })
    @tag
    static async getNotes(ctx, next) {
        // var page = ctx.query.page || 0
        // var size = ctx.query.size || 10
        var user = ctx.state.user;
        var result = await Note.find()//{ 'ownerId':  user.id }
        result.map((item) =>{
             item.isLock = item.isLock && note.ownerId != user.userId
             return item
        })
            // .limit(size).skip(page * size)
        ctx.body = responseWrapper(result)
    }

    @request('get', '/api/note/download/{id}')
    @summary("获取文件")
    @tag
    @rpath({ id: { type: 'string', required: true } })
    static async getNoteFile(ctx, next) {
        const { id } = ctx.validatedParams;
        var filePath = path.join(fileDir, id + '.text')
        console.log('filePath',filePath)
        var filename = path.basename(filePath)
        // var mimetype = mime.lookup(file)
        filename = filename.replace(/([\u4e00-\u9fa5])/g, (str) => encodeURIComponent(str) )
        ctx.body = await fs.createReadStream(filePath)
        ctx.set('Content-disposition',
            'attachment; filename=' + filename)
        ctx.set('Content-type', 'text/plain')
    }

}

